import { http, sendTransaction, connect, getConnections } from "@wagmi/core";
import { encodeFunctionData, parseEther, parseGwei, parseUnits } from "viem";
import { kaia } from "@wagmi/vue/chains";
import { config } from "@/utils/wagmi";
import { i18n } from "../main";

function getERC20TransferData(to, amount) {
  const abi = [
    {
      name: "transfer",
      type: "function",
      inputs: [
        { name: "to", type: "address" },
        { name: "value", type: "uint256" },
      ],
      outputs: [{ name: "", type: "bool" }],
    },
  ];
  return encodeFunctionData({
    abi,
    functionName: "transfer",
    args: [to, amount],
  });
}
//充值USDT
export const handleTransferUSDT = async (
  contractAddress,
  toAddress,
  amount
) => {
  try {
    const result = await sendTransaction(config, {
      chainId: kaia.id,
      to: contractAddress, // ERC20 合约地址
      value: 0, // 主币转移金额为 0，因为我们转移的是 ERC20 代币
      data: getERC20TransferData(
        toAddress, // 转移的目标地址
        parseEther(amount) // 转移的代币数量，这里使用 parseEther 将字符串金额转换成 wei
      ),
    });
    console.log(`output->result`, result);
    return result;
  } catch (e) {
    console.log(`output->`, e);
    throw new Error();
  }
};
// 充值NFT
export const handleTransferNFT = (contractAddress, from, to, id, value) => {
  const result = sendTransaction(config, {
    chainId: kaia.id,
    to: contractAddress, // ERC20 合约地址
    value: 0, // 主币转移金额为 0，因为我们转移的是 ERC20 代币
    data: getERC20TransferNFTData(from, to, id, value),
  });
  return result;
};
function getERC20TransferNFTData(from, to, id, value) {
  const abi = [
    {
      inputs: [
        {
          internalType: "address",
          name: "from",
          type: "address",
        },
        {
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "id",
          type: "uint256",
        },
        {
          internalType: "uint256",
          name: "value",
          type: "uint256",
        },
        {
          internalType: "bytes",
          name: "data",
          type: "bytes",
        },
      ],
      name: "safeTransferFrom",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
  ];
  return encodeFunctionData({
    abi,
    functionName: "safeTransferFrom",
    args: [from, to, id, value, "0x"],
  });
}
